<?php
namespace Mapi\Controller;
use Think\Controller\RestController;

class RegController extends RestController {    

    protected $allowMethod    = array('get','post','put'); // REST允许的请求类型列表
    protected $allowType      = array('html','xml','json'); // REST允许请求的资源类型列表

    /**
     * 用户注册
     * @return [type] [description] 
     */
    public function loginByApi() {
        apigetpost(); 
    	$userModel = D('User');
         // print_r($_POST);exit;
		if($userModel->create($_POST, 4)){            
           //  $uid = $userModel->save();
            
           // $userinfo=session('userinfo');
           
            $account = I('post.username');
            $passWord = I('post.password');

            $map['password'] = md5(C('PWD_SALT') . $passWord);
            $map['mobile'] = $account;
            $userinfo = $userModel->alias('u')->join('__USER_INFO__ AS ui ON ui.uid = u.uid')->where($map)->find();   
            if(!$userinfo) {
                $map2['password'] = md5(C('PWD_SALT') . $passWord);
                $map2['realname'] = $account;
                $userinfo = $userModel->alias('u')->join('__USER_INFO__ AS ui ON ui.uid = u.uid')->where($map2)->find();
                if(!$userinfo) {
                    $map3['password'] = md5(C('PWD_SALT') . $passWord);
                    $map3['username'] = $account;
                    $userinfo = $userModel->alias('u')->join('__USER_INFO__ AS ui ON ui.uid = u.uid')->where($map3)->find();
                }
            }
                                  
            if(!empty($userinfo) && $userinfo['uid']){
                $user_login_info=D('UserLoginInfo');
                if($user_login_info->create()){
                    // 删除记录
                    // $login_info = D('UserLoginInfo')->where(array('uid' => $userinfo['uid']))->find();
                    // setlog($userinfo['mobile'], $userinfo['uid'], CONTROLLER_NAME, ACTION_NAME, $login_info['clienttype'], $login_info['devicename'], $login_info['appversion']);
                    // 删除重复的用户
                    // $user_login_info->where(array('uid' => $userinfo['uid']))->delete();
                    // 删除重复的设备ID
                    // $user_login_info->where(array('channelid' => I('post.channelId')))->delete(); 


                    $user_login_info->where(['uid' => $userinfo['uid'], 'valid_status' => 1])->save(array(
                        'valid_status' =>2,
                        'update_time' => time(),
                    ));

                    $user_login_info->uid = $userinfo['uid'];
                    $token = md5($userinfo['uid'].'-'.time());
                    $user_login_info->token = $token;

                    // $reporter = M('UserInfo')->where(array('uid' => $userinfo['uid']))->find();
                    // if($reporter) {
                        $user_login_info->reporter_id = $userinfo['uid'];
                        // 频道
                        $rName = M('Channel')->where(['chid' => $userinfo['userchannel']])->find();

                        // 岗位
                        $jName = M('Job')->where(['jid' => $userinfo['userjobs']])->find();

                        $user_login_info->dept_id = $userinfo['userchannel'];
                        $user_login_info->org_id = $rName['org_id'];                        

                    // }
                    
                    if($user_login_info->add()){

                        $info = M('UserInfo')->field('userchannel,userjobs')->where(array('uid' => $userinfo['uid']))->find();

                        $arr['resultCode']=0;
                        $arr['message'] = '';
                        $arr['userId'] = $userinfo['uid'];
                        $arr['userToken'] = $token;
                        $arr['userName'] = $userinfo['username'];
                        $arr['fullName'] = $userinfo['realname']?$userinfo['realname']:'';
                        $arr['mobile'] = $userinfo['mobile']?$userinfo['mobile']:'';
                        $arr['mediaName'] = $userinfo['workunit']?$userinfo['workunit']:'';
                        $arr['status'] = $userinfo['status'];
                        $arr['channelName'] = M('Channel')->where(array('chid' => $info['userchannel']))->getField('name');
                        $arr['positionName'] = M('Job')->where(array('jid' => $info['userjobs']))->getField('name');
                        $userModel->save();
                        
                    }else{
                       $arr=array(
                            'resultCode'=>-1,
                            'message'=>'服务器操作错误'
                        ); 
                    }
                }else { //create失败
                    $arr=array(
                        'resultCode'=>-1,
                        'message'=>'服务器操作错误'
                    ); 
                }
            }else{
                $arr=array(
                    'resultCode'=>-1,
                    'message'=>'服务器操作错误'
                );
            }    
		}else { //create失败
           
             $arr['resultCode']=1;
             $arr['message']=$userModel->getError();
		}
       // dump($arr);
        $this->ajaxReturn($arr);
    }


    /**
     * 忘记密码
     * @return [type] [description]
     */
    function forgetPwdByApi(){
        apigetpost();
        $user=D('User');
        if($user->create(I('post.'),5)){            
            $userinfo=M('User')->alias('u')->join('__USER_INFO__ AS ui ON ui.uid = u.uid')->where(array('mobile'=>I('post.mobile')))->find();
            if($userinfo){
                    $user->uid=$userinfo['uid'];
                    if($user->save()){
                        $user_login_info=D('UserLoginInfo');  
                        $user_login_info->create();  
                        $user_login_info->where(array('uid' => $userinfo['uid']))->delete();
                        $user_login_info->uid = $userinfo['uid'];
                        $token = md5($userinfo['uid'].'-'.time());
                        $user_login_info->token = $token;

                        $user_login_info->add();                   

                        // $token=md5($userinfo['uid'].'-'.C('PWD_SAlT'));
                        $arr['resultCode']=0;
                        $arr['message']='';
                        $arr=array_merge($arr,array(
                            "userId"=>$userinfo['uid'],
                            "userToken"=>$token,
                            "userName"=>$userinfo['username']?$userinfo['username']:'',
                            "fullName"=>$userinfo['realname']?$userinfo['realname']:'',
                            "mobile"=>$userinfo['mobile']?$userinfo['mobile']:'',
                            "mediaName"=>$userinfo['workunit']?$userinfo['workunit']:'',
                            "status"=>$userinfo['status']?$userinfo['status']:'',
                            'channelName' => M('Channel')->where(array('chid' => $userinfo['userchannel']))->getField('name'),
                            'positionName' => M('Job')->where(array('jid' => $userinfo['userjobs']))->getField('name'),
                        ));
                        // F($token, $userinfo['uid']);
                        // setlog($userinfo['realname'], $userinfo['uid'], CONTROLLER_NAME, ACTION_NAME); 
                    }else{
                        $arr=array(
                            'resultCode'=>-1,
                            'message'=>'服务器操作错误'
                        );
                    }
                
            }else{
                $arr=array(
                    'resultCode'=>1,
                    'message'=>'手机号未注册'
                );
            }
        }else{
               $arr['resultCode']=1;
                $arr['message']=$user->getError();
            }
        //dump($arr);
        $this->ajaxReturn($arr);
    }

/**
     * 发送验证码API
     */
    public function sendCodeByApi() {
        apigetpost();
        $mobile = I('post.mobile'); 
        $flag= I('post.flag');

        if(!$mobile) {
            $message['resultCode'] = 1;
            $message['message'] = '未填手机号';
            $this->ajaxReturn($message);
        } elseif(!preg_match('/^1[3|4|5|8]\d{9}$/', $mobile)) {
            $message['resultCode'] = 1;
            $message['message'] = '手机号格式不正确';   
            $this->ajaxReturn($message);        
        }

        $id = M('UserInfo')->where(array('mobile' => $mobile))->getField('uid');
        if($id && $flag == 0) {
            $message['resultCode'] = 1;
            $message['message'] = '手机号已注册'; 
            $this->ajaxReturn($message); 
        } elseif(!$id && $flag == 1) {
            $message['resultCode'] = 1;
            $message['message'] = '手机未注册'; 
            $this->ajaxReturn($message); 

        } else {
            $code = generateCode();
            $res = sendSMS($mobile, $code);
            $res=true;
            if($res) {
                $prefix = md5($mobile);
                F($prefix, array('smsCode' => $code, 'smsTime' => time(), 'smsMobile' => $mobile));

                $username = M('UserInfo')->where(array('mobile' => $mobile))->getField('uid');
                // setlog($mobile, $id, CONTROLLER_NAME, ACTION_NAME);   

                $message['resultCode'] = 0;
                $message['message'] = $code;
                $this->ajaxReturn($message);            
            } else {
                $message['resultCode'] = 1;
                $message['message'] = '短信发送失败，请重新发送';   
                $this->ajaxReturn($message);                
            }
        }
    }

    /**
     * 校验手机验证码
     * @return [type] [description]
     */
    public function verifyCodeByApi() {
        $mobile = I('get.mobile', '');
        $code = I('get.code', '');

        if(!$mobile) {
            $message['resultCode'] = 1;
            $message['message'] = '手机号不能为空';
            $this->ajaxReturn($message);            
        } elseif(!$code) {
            $message['resultCode'] = 1;
            $message['message'] = '验证码不能为空';        
            $this->ajaxReturn($message);
        }

        $data = F(md5($mobile));
        // $this->ajaxReturn($data);
        // exit; 

        $sTime = 10 * 60;
        if($mobile != $data['smsMobile']) {
            $message['resultCode'] = 1;
            $message['message'] = '填写的手机号与发短信的手机号不匹配';  
            $this->ajaxReturn($message);        
        } elseif((time() - $data['smsTime']) > $sTime){
            F(md5($mobile), null);
            $message['resultCode'] = 1;
            $message['message'] = '验证码过期';  
            $this->ajaxReturn($message);
        } elseif($code != $data['smsCode']) {
            $message['resultCode'] = 1;
            $message['message'] = '验证码不正确'; 
            $this->ajaxReturn($message);            
        } else {
            F(md5($mobile), null);
            // setlog($mobile, 0, CONTROLLER_NAME, ACTION_NAME); 
            $message['resultCode'] = 0;
            $message['message'] = '验证通过';
            $this->ajaxReturn($message);                
        }
    }

    /**
     * 注册API
     * @return [type] [description]
     */
    public function registerByApi() {
        apigetpost();
        $dataPost['mobile']= I('post.mobile', '');
        $dataPost['password'] = I('post.password', '');
        $dataPost['realname'] = I('post.fullName', '');
        $dataPost['medianame'] = I('post.mediaName', '');
        $dataPost['clienttype'] = I('post.clientType', '');
        $dataPost['devicename'] = I('post.deviceName', '');
        $dataPost['appversion'] = I('post.appVersion', '');
        $dataPost['channelid'] = I('post.channelId', '');

        if(!$dataPost['mobile']) {
            $message['resultCode'] = 1;
            $message['message'] = '手机号不能为空';    
            $this->ajaxReturn($message);            
        } elseif(preg_match('/^1[3|4|5|7|8]\d{9}$/', $dataPost['mobile'])) {
            $info = M('UserInfo')->where(array('mobile' => $dataPost['mobile']))->getField('uid');
            if($info) {
                $message['resultCode'] = 1;
                $message['message'] = '手机号已被注册';    
                $this->ajaxReturn($message);                
            }
        } elseif(!$dataPost['password']) {
            $message['resultCode'] = 1;
            $message['message'] = '密码不能为空'; 
            $this->ajaxReturn($message);        
        }
        
        $time = time();
        $userDataGet['username'] = 'm' . $time;
        $userDataGet['password'] = md5(C('PWD_SALT') . $dataPost['password']);
        $userDataGet['createtime'] = $time;
        $userDataGet['lastlogintime'] = $time;
        $userDataGet['lastloginip'] = get_client_ip();
        $userRes = D('User')->add($userDataGet);
        if($userRes) {
            $userInfoDataGet['uid'] = $userRes;
            $userInfoDataGet['mobile'] = $dataPost['mobile'];
            $userInfoDataGet['realname'] = $dataPost['realname'];
            $userInfoDataGet['realnamepy'] = zh2py($dataPost['realname']);
            $userInfoDataGet['workunit'] = $dataPost['medianame'];
            $userInfoRes = M('UserInfo')->add($userInfoDataGet);
            if($userInfoRes) {
                M('UserLoginInfo')->where(array('uid' => $userRes))->delete();

                $loginData['uid'] = $userRes;
                $loginData['token'] = md5($userRes . '-' . C('PWD_SALT'));
                $loginData['workunit'] = $dataPost['medianame'];
                $loginData['clienttype'] = $dataPost['clienttype'];
                $loginData['devicename'] = $dataPost['devicename'];
                $loginData['appversion'] = $dataPost['appversion'];
                $loginData['channelid'] = $dataPost['channelid'];
                $loginData['logintime'] = time();
                $loginData['loginip'] = get_client_ip();
                $loginRes = M('UserLoginInfo')->add($loginData);
                if($loginRes) {
                    $tokenData['uid'] = $userRes;
                    $tokenData['token'] = $loginData['token'];

                    $info['userId'] = $userRes;
                    $info['userToken'] = $tokenData['token'];
                    $info['userName'] = $userDataGet['username'];
                    $info['fullName'] = $userInfoDataGet['realname'];
                    $info['mobile'] = $dataPost['mobile'];
                    $info['mediaName'] = $dataPost['medianame'];
                    $info['status'] = 0;
                    $message = $info;
                    // setlog($dataPost['mobile'], $userRes, CONTROLLER_NAME, ACTION_NAME);

                    $message['resultCode'] = 0; 
                    $message['message'] = '';   
                    $this->ajaxReturn($message);                    
                } else {
                    $message['resultCode'] = -1;
                    $message['message'] = '注册失败';   
                    $this->ajaxReturn($message);                
                }
            } else {
                    $message['resultCode'] = -1;
                    $message['message'] = '注册失败';   
                $this->ajaxReturn($message);
            }
        } else {
            $message['resultCode'] = -1;
            $message['message'] = '注册失败';           
            $this->ajaxReturn($message);
        }
    }

    /**
     * 退出
     * @return [type] [description]
     */
    public function logout() {
        // $token = I('post.userToken'); 
        // F($token, null);
       // $token = I('server.HTTP_USERTOKEN');
       //  $user_login_info = D('UserLoginInfo');
       //  $info = $user_login_info->where(array('token' => $token))->find();
       //  if($info['uid']) {
       //      $user_login_info->where(array('uid' => $info['uid']))->delete();
       //  }
        
       //  session(null);
       //  $username = M('UserInfo')->where(array('uid' => $info['uid']))->getField('realname');
       //  // setlog($username, $info['uid'], CONTROLLER_NAME, ACTION_NAME, $info['clienttype'], $info['devicename'], $info['appversion']);

       //  $message['resultCode'] = 0;
       //  $message['message'] = '';           
       //  $this->ajaxReturn($message); 

        $token = I('server.HTTP_USERTOKEN');
        $userLoginInfoModel = M('UserLoginInfo');
        $info = $userLoginInfoModel->where(['token' => $token])->find();
        if($info['uid']) {
            $userLoginInfoModel->where(['token' => $token, 'valid_status' => 1])->save(array(
                'valid_status' => 0,
                'update_time' =>time(), 
            ));
        }

        session(null);

        $message['resultCode'] = 0;
        $message['message'] = '';
        $this->ajaxReturn($message);

    }

    private function getRegConfig($client_type,$version){
        if($version){
            $sysconfig=M('system_config');
            $regType= $sysconfig->getByConfig('RegType');
            if($regType){
               if($regType['value']==1){
                   $res=M('reg_config')->field('can_reg')->where(array('client_type'=>$client_type,'version'=>$version))->find();
                   if($res){
                       $message['resultCode'] = 0;
                       $message['message'] = '';
                       $message['canReg'] = $res['can_reg'];
                   }else{
                       $message['resultCode'] = 0;
                       $message['message'] = '';
                       $message['canReg'] = 0;
                   }
               }else{
                   $message['resultCode'] = 0;
                   $message['message'] = '';
                   $message['canReg'] = 0;
               }
            }else{
                $message['resultCode'] = -1;
                $message['message'] = '服务器查询错误';
            }
        }else{
            $message['resultCode'] = 1;
            $message['message'] = '缺少regKey参数';
        }
        return $message;
    }

    public function getAndroidRegConfig(){
        $version=I('get.version');
        $this->ajaxReturn($this->getRegConfig('ANDROID',$version));
    }

    public function getIOSRegConfig(){
        $version=I('get.version');
        $this->ajaxReturn($this->getRegConfig('IOS',$version));
    }
}